package com.xn2001.service.impl;

import com.xn2001.entity.LevelCatalog;
import com.xn2001.entity.LevelCatalogVo;
import com.xn2001.mapper.LevelCatalogMapper;
import com.xn2001.service.LevelCatalogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 乐心湖
 * @since 2020-07-18
 */
@Service
public class LevelCatalogServiceImpl extends ServiceImpl<LevelCatalogMapper, LevelCatalog> implements LevelCatalogService {

    @Override
    public List<LevelCatalogVo> info() {
        //取出所有的内容
        List<LevelCatalog> levelCatalogs = baseMapper.selectList(null);
        //创建一个需要返回的vo展示集合对象
        List<LevelCatalogVo> levelCatalogVos = new ArrayList<>();
        //所有内容进行遍历
        for (LevelCatalog levelCatalog : levelCatalogs) {
            //找出一级分类，赋值到vo类，加入到集合中去
            if (levelCatalog.getParentId() == 0){
                LevelCatalogVo levelCatalogVo = new LevelCatalogVo();
                BeanUtils.copyProperties(levelCatalog,levelCatalogVo);
                //为一级分类设置子分类
                levelCatalogVo.setChildren(getChildrens(levelCatalogVo,levelCatalogs));
                levelCatalogVos.add(levelCatalogVo);
            }
        }
        return levelCatalogVos;
    }

    @Override
    public List<LevelCatalogVo> info2() {
        return baseMapper.info2(0L);
    }

    private List<LevelCatalogVo> getChildrens(LevelCatalogVo root, List<LevelCatalog> levelCatalogs) {
        //由于子分类下可能还有子分类，因此依旧需要创建一个需要返回的vo展示集合对象
        List<LevelCatalogVo> levelCatalogVos = new ArrayList<>();
        //依旧将所有内容进行遍历
        for (LevelCatalog levelCatalog : levelCatalogs) {
            //取出相应子类，加到集合中并返回
            if (root.getId().equals(levelCatalog.getParentId())){
                LevelCatalogVo levelCatalogVo = new LevelCatalogVo();
                BeanUtils.copyProperties(levelCatalog,levelCatalogVo);
                //使用递归，循序渐进式设置完各大小级分类
                levelCatalogVo.setChildren(getChildrens(levelCatalogVo,levelCatalogs));
                //最总加入到集合中去
                levelCatalogVos.add(levelCatalogVo);
            }
        }
        return levelCatalogVos;
    }

}
